﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LPY.LeHealth.WebSite.Common
{
    public class TokenAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var tokens = filterContext.RequestContext.HttpContext.Request.Headers.GetValues("token");
            if(tokens.Length>0 && tokens[0]!="null")
            {
                //解析token，校验是否失效
                var secretKey = ConfigurationManager.AppSettings["jwt_secret_key"];
                try
                {
                    var jsonPayload = JWT.JsonWebToken.DecodeToObject<Dictionary<string, object>>(tokens[0], secretKey);
                }
                catch (JWT.SignatureVerificationException sve)
                {
                    //失效：禁止请求 403
                    filterContext.Result = new ContentResult { Content = "403" };
                }
                catch (ArgumentException ae)
                {
                    //参数错误
                    filterContext.Result = new ContentResult { Content = "403" };
                }
                catch (Exception ex)
                {
                    //其他异常 服务器错误：500
                    filterContext.Result = new ContentResult { Content = "500" };
                }
            }
        }
    }
}